package com.bawei.day12_broadcastrecevier.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bawei.day12_broadcastrecevier.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class TwoFragment extends Fragment {
    private TextView textView;
    private MySticyRecevier mySticyRecevier;
    public TwoFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_two, container, false);
        textView = view.findViewById(R.id.tv);
        //注册
        mySticyRecevier = new MySticyRecevier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.bawei.nianxing");
        getActivity().registerReceiver(mySticyRecevier,intentFilter);
        return view;
    }
    //解除注册
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(mySticyRecevier);
    }
    //广播接受者
    class MySticyRecevier extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bawei.nianxing".equals(intent.getAction())){
                Bundle bundle = intent.getExtras();
                String message = bundle.getString("message");
                textView.setText(message);
            }
        }
    }

}
